
#include "SingleList.h"
#include "List4_Malloc.H"


SingleList*  NewSingleList(void)
{
	SingleList* sl = (SingleList*)malloc(sizeof(SingleList));
	if(sl == 0)return 0;	 
	sl->next = 0;
	sl->num = 0;		 
	return sl;
}


SingleListNodeStr*   SingleList_InsertEnd(SingleList* list, SingleListNode* node)
{ 
    SingleList* current = list;
    SingleListNodeStr* newnode = (SingleListNodeStr*)malloc(sizeof(SingleListNodeStr));
	if(newnode == 0) return 0;
	newnode->next = 0;
	newnode->node = node;
    for(; current->next != 0;)
        current = current->next;
	current->next = newnode;     
    list->num ++;
//	debug("newnode addr = %#X\r\n",(u32)newnode);
    return newnode;
}


SingleListNodeStr* SingleList_InsertBefore(SingleList* list, SingleListNode* objnode, SingleListNode* newnode)
{
	SingleList* current = list;
	SingleListNodeStr* new = (SingleListNodeStr*)malloc(sizeof(SingleListNodeStr));
	if(new == 0) return 0;
	new->node = newnode;
    for(; current->next != 0;)
    {
		if(current->next == objnode)	
		{
			current->next = new;
			new->next = objnode;
			break;
		}
        current = current->next;
    }
	list->num ++;
	return new;	
}


SingleListNode* SingleList_DeleteNode(SingleList* list, SingleListNode* node)
{
	SingleList* current = list;
	void* back;
    for(;current->next != 0; )
    {
        if( ((SingleListNodeStr*)(current->next))->node == node ) break;
        current = current->next;
    }
	if(current->next == 0) return 0;
	back =  current->next;
    current->next = ((SingleListNodeStr*)(current->next))->next;
	free(back);
	list->num --;
    return (SingleListNode*)current;
}


listHead* SingleList_Iterator(listHead** node)
{
	if(*node) *node = ((SingleListNodeStr*)*node)->next;
	return *node;
}


void FreeSingList(SingleList* list)
{
	SingleListNode* node = (SingleListNode*)list;
	while(SingleList_Iterator(&node))
		 SingleList_DeleteNode(list,node);
	free(list);
}


void SingleList_MoveEndNode(SingleList* list, SingleListNode* node)
{
    SingleList* current = list;
	void* back;
    for(;current->next != 0; )
    {
        if( ((SingleListNodeStr*)(current->next))->node == node )
        	break;
        current = current->next;
    }
	if(current->next == 0)return;
	if(((SingleListNodeStr*)(current->next))->next)
	{
		back = current->next;
		current->next = ((SingleListNodeStr*)(current->next))->next;
	    for(; current->next != 0;)
	        current = current->next;
	    current->next = back;
	    ((SingleList*)back)->next = 0;
	}
}


SingleListNode* SingleList_GetNode(SingleList* list,unsigned int num)
{
	SingleListNode* node = (SingleListNode*)list;
	if(list->num == 0) return 0;
	if(num > (list->num - 1)) return 0;
	while(SingleList_Iterator(&node) && num != 0) num --;
	return node;	
}

// 遍历输出单链表所有的节点
void ShowSingleList(SingleList* list)
{
	listHead* node = list;
	debug("Show SingleList(%#x):\r\n",(u32)list);
	while(SingleList_Iterator(&node))
	{
		debug("%s\r\n",SingeListGetnode(u8*,node));
	}
}

